/***
 *  Copyright (c) 2012 yanghui
 *  Author: yanghui1986527@gmail.com
 *  http://code.google.com/p/gravatar4android/
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.snowdream.gravatar4android.util;

import android.text.TextUtils;

import java.security.MessageDigest;

public class EncryptUtil {

    private static EncryptUtil instance = null;

    private EncryptUtil() {
    }
    
    public synchronized static EncryptUtil getInstance() {
        if (instance == null) {
            instance = new EncryptUtil();
        }
        return instance;
    }

    private final char hexDigits[] = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };

    private String byteToHexString(byte[] tmp) {
        String s;
        char str[] = new char[16 * 2];
        int k = 0;
        for (int i = 0; i < 16; i++) {
            byte byte0 = tmp[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        s = new String(str);
        return s;
    }

    /**
     * get the MD5 value of the string
     * 
     * @param s  a String
     * @return the MD5 value of the string s.
     */
    public final String md5Hex(String s) {
        return encrypt32BString(s, "MD5");
    }

    private final String encrypt32BString(String s, String type) {
        String result = "";
        if (TextUtils.isEmpty(s)) {
            return result;
        }
        try {
            MessageDigest md = MessageDigest.getInstance(type);
            md.update(s.toString().getBytes("UTF-8"));
            byte[] res = md.digest();
            result = byteToHexString(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
